<?php

namespace App\Http\Controllers\API\Home;

use DB;
use Auth;
use App\Models\API\Tweet;
use App\Events\UserLoginIn;
use App\Models\API\Friend;
use App\Models\API\Activity;
use Illuminate\Http\Request;
use Illuminate\Pagination\Paginator;
use App\Http\Controllers\API\APIController;
use Illuminate\Pagination\LengthAwarePaginator;

class HomeController extends APIController
{
    public function index(Request $request)
    {
        $userId = Auth::user()->id;

    	// 获取所有用户Id
    	$friends = Friend::where('companion_id', $userId)->pluck('user_id')->toArray();
    	$users = array_prepend($friends, $userId);

        $activities = Activity::whereIn('user_id', $users)
    	->join('users', 'activities.user_id', '=', 'users.id')
        ->select('activities.*', 'users.user_name', 'users.user_img')
        ->withCount('activityApply', 'activityJoin')
    	->get()->toArray();

        $tweets = Tweet::whereIn('tweets.user_id', $users)
    	->join('users', 'tweets.user_id', '=', 'users.id')
        ->select('tweets.*', 'users.user_name', 'users.user_img')
    	->get()->toArray();

        // 创建合集 array_collapse() 排序
    	$collection = collect(array_merge($activities, $tweets));
    	$sorted = $collection->sortBy('created_at');
    	$sorted->values()->all();
    	$arr = $sorted->toArray();

    	// 分页
    	if ($request->has('page')) {
			$currentPage = $request->input('page');
			$currentPage = $currentPage <= 0 ? 1 :$currentPage;
		} else {
			$currentPage = 1;
		}
    	$perPage = 20;
    	$item = array_slice($arr, ($currentPage-1)*$perPage, $perPage);
    	$total = count($arr);
    	$paginator =new LengthAwarePaginator($item, $total, $perPage, $currentPage, [
		    'path' => Paginator::resolveCurrentPath(),
		    'pageName' => 'page',
		]);

    	return response()->json($paginator, 200);
    }

    public function fetch()
    {
        $userId = Auth::user()->id;
        
    	event(new UserLoginIn($userId));
    }
}
